package com.eight.paper.admin.controller;

import com.alibaba.fastjson2.JSONObject;
import com.eight.common.annotation.Log;
import com.eight.common.constant.ExamConstants;
import com.eight.common.core.controller.BaseController;
import com.eight.common.core.domain.AjaxResult;
import com.eight.common.core.domain.entity.QuestionRepo;
import com.eight.common.core.page.TableDataInfo;
import com.eight.common.core.redis.RedisCache;
import com.eight.common.enums.BusinessType;
import com.eight.common.exception.ServiceException;
import com.eight.common.utils.StringUtils;
import com.eight.common.utils.poi.ExcelUtil;
import com.eight.common.utils.uuid.IdUtils;
import com.eight.paper.admin.domain.model.*;
import com.eight.paper.admin.domain.model.enums.QuestionTypeEnum;
import com.eight.paper.admin.service.IQuestionBaseService;
import com.eight.paper.admin.service.IQuestionRepoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.List;

/**
 * 试题管理Controller
 * 
 * @author 爱考线上考试系统
 * @date 2023-10-04
 */
@Api(value = "试题管理", tags = "试题管理")
@RestController
@RequestMapping("/paper/question")
public class QuestionBaseController extends BaseController
{
    @Autowired
    private IQuestionBaseService questionBaseService;
    @Autowired
    private IQuestionRepoService questionRepoService;
    @Resource
    private ThreadPoolTaskExecutor threadPoolTaskExecutor;
    @Autowired
    private RedisCache redisCache;

    /**
     * 查询试题管理列表
     */
    @ApiOperation(value = "查询试题管理列表")
    @GetMapping("/list")
    public TableDataInfo list(QuestionListBody questionBase)
    {
        startPage();
        List<QuestionListBody> list = questionBaseService.selectQuestionBaseList(questionBase);
        list.stream().forEach(q->{
            String questionType=q.getQuestionType();
            q.setContent("");
            if(StringUtils.isNotNull(questionType)) {
                q.setQuestionTypeName(QuestionTypeEnum.fromCode(questionType).getName());
            }
        });
        return getDataTable(list);
    }

    /**
     * 导出试题管理列表
     */
    @PreAuthorize("@ss.hasPermi('paper:question:export')")
    @Log(title = "试题管理", businessType = BusinessType.EXPORT)
    @PostMapping("/export")
    public void export(HttpServletResponse response, QuestionListBody questionBase)
    {
        List<QuestionListBody> list = questionBaseService.selectQuestionBaseList(questionBase);
        list.stream().forEach(q->{
            String questionType=q.getQuestionType();
            if(StringUtils.isNotNull(questionType)) {
                q.setQuestionTypeName(QuestionTypeEnum.fromCode(questionType).getName());
            }
        });
        ExcelUtil<QuestionListBody> util = new ExcelUtil<QuestionListBody>(QuestionListBody.class);
        util.exportExcel(response, list, "试题基础数据");
    }

    /**
     * 获取试题详细信息
     */
    @ApiOperation(value = "获取试题详细信息")
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Integer id)
    {
        return success(questionBaseService.selectQuestionBodyById(id));
    }

    /**
     * 编辑试题
     */
    @ApiOperation(value = "编辑选择题")
    @PostMapping("editChoice")
    public AjaxResult editChoice(@RequestBody QuestionChoiceBody questionChoiceBody)
    {
        if (StringUtils.isNotNull(questionChoiceBody)) {
            return toAjax(questionBaseService.editQuestion(questionChoiceBody, questionChoiceBody.getTitle(),JSONObject.toJSONString(questionChoiceBody)));
        } else {
            throw new ServiceException("试题为空，保存异常");
        }
    }

    /**
     * 编辑主观试题
     */
    @ApiOperation(value = "编辑主观试题")
    @PostMapping("editAnswer")
    public AjaxResult editAnswer(@RequestBody QuestionAnswerBody questionAnswerBody)
    {
        if (StringUtils.isNotNull(questionAnswerBody)) {
            return toAjax(questionBaseService.editQuestion(questionAnswerBody, questionAnswerBody.getTitle(),JSONObject.toJSONString(questionAnswerBody)));
        } else {
            throw new ServiceException("试题为空，保存异常");
        }
    }

    @ApiOperation(value = "编辑B1配伍题")
    @PostMapping("/editB1")
    public AjaxResult editB1(@RequestBody @Validated QuestionB1Body questionB1Body) {
        if (StringUtils.isNotNull(questionB1Body)) {
            return toAjax(questionBaseService.editQuestion(questionB1Body, questionB1Body.getTitle(),JSONObject.toJSONString(questionB1Body)));
        } else {
            throw new ServiceException("试题为空，保存异常");
        }
    }

    @ApiOperation(value = "编辑A3A4题")
    @PostMapping("/editA3A4")
    public AjaxResult editA3A4(@RequestBody @Validated QuestionA3A4Body questionA3A4Body) {
        if (StringUtils.isNotNull(questionA3A4Body)) {
            return toAjax(questionBaseService.editQuestion(questionA3A4Body, questionA3A4Body.getTitle(),JSONObject.toJSONString(questionA3A4Body)));
        } else {
            throw new ServiceException("试题为空，保存异常");
        }
    }

    @ApiOperation(value = "编辑判断题")
    @PostMapping("/editTF")
    public AjaxResult editTF(@RequestBody @Validated QuestionTFBody questionTFBody) {
        if (StringUtils.isNotNull(questionTFBody)) {
            return toAjax(questionBaseService.editQuestion(questionTFBody, questionTFBody.getTitle(),JSONObject.toJSONString(questionTFBody)));
        } else {
            throw new ServiceException("试题为空，保存异常");
        }
    }

    /**
     * 删除试题管理
     */
    @ApiOperation(value = "删除试题管理")
    @PreAuthorize("@ss.hasPermi('paper:question:remove')")
    @Log(title = "试题管理", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Integer[] ids)
    {
        return toAjax(questionBaseService.deleteQuestionBaseByIds(ids));
    }

    /**
     * 获取题库树列表
     */
    @PreAuthorize("@ss.hasPermi('paper:question:list')")
    @GetMapping("/repoTree")
    public AjaxResult deptTree(QuestionRepo repo)
    {
        return success(questionRepoService.selectRepoTreeList(repo));
    }

    @ApiOperation(value = "试题导入")
    @PreAuthorize("@ss.hasPermi('paper:question:importQuestion')")
    @PostMapping("/importQuestion")
    public AjaxResult importQuestion(MultipartFile file) throws Exception {
        Long userId = getUserId();
        Long deptId = getDeptId();
        String uuid = IdUtils.simpleUUID();
        redisCache.setCacheObject(String.format(ExamConstants.QUESTION_IMPORT_PRESET_AMOUNT,uuid), -1);
        ExcelUtil<QuestionTemplate> util = new ExcelUtil<>(QuestionTemplate.class);
        List<QuestionTemplate> questions = util.importExcel(file.getInputStream());
        HashMap<String,Integer> repoIdMap = questionBaseService.validateRepoName(questions);
        threadPoolTaskExecutor.execute(() -> {
            questionBaseService.importQuestions(questions,uuid, userId,deptId,repoIdMap);
        });

        return AjaxResult.success(uuid);
    }

    @ApiOperation(value = "试题导入进度监测")
    @PreAuthorize("@ss.hasPermi('paper:question:importMonitor')")
    @GetMapping("/importMonitor/{uuid}")
    public AjaxResult importMonitor(@PathVariable String uuid) {
        MonitorResult result = questionBaseService.importMonitor(uuid);
        return AjaxResult.success(result);
    }

    @ApiOperation(value = "导出试题,type:1-excel,2-word,3-pdf")
    @PreAuthorize("@ss.hasPermi('paper:question:exportQuestion')")
    @PostMapping("/exportQuestion/{type}/{ids}")
    public void exportQuestion(HttpServletResponse response,@PathVariable String type, @PathVariable Integer[] ids) {
        questionBaseService.exportQuestion(response,type,ids);
    }
}
